package com.hn.zhijian.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hn.zhijian.base.controller.BaseController;
import com.hn.zhijian.base.model.request.DataGrid;
import com.hn.zhijian.base.model.request.PageRequest;
import com.hn.zhijian.utils.BeanCopier;

import java.util.List;

/**
 * @author carl chen
 * @Classname AbstractController
 * @Description 增强BASE层方法
 * @Date 2019/10/29 20:08
 */
public abstract class AbstractController extends BaseController {
    /**
     * 构建DataGrid.
     * @param page
     * @return
     */
    public <T> DataGrid buildDataGrid(Page<T> page) {
        DataGrid dataGrid = new DataGrid();
        dataGrid.setRows(page.getRecords());
        dataGrid.setTotal(page.getTotal());
        return dataGrid;
    }

    /**
     * 构建DataGrid.
     *
     * @param rows
     * @param total
     * @return
     */
    public <T> DataGrid buildDataGrid(List<T> rows, int total) {
        DataGrid dataGrid = new DataGrid();
        dataGrid.setRows(rows);
        dataGrid.setTotal(new Long(total));
        return dataGrid;
    }

    /**
     * 分页
     * @param pageRequest
     * @param <T>
     * @return
     */
    protected <T> Page<T> getPagination(PageRequest pageRequest) {
        Page<T> page =  new Page<T>(pageRequest.getPage(), pageRequest.getRows());
        return page;
    }


    /**
     * Page对象转换
     * @param source
     * @param destinationClass
     * @return
     */
    public Page convert(Page source, Class destinationClass) {
        List result =  BeanCopier.copyJSONList(source.getRecords(),destinationClass) ;
        source.setRecords(result);
        return source;
    }

    public <T> T convertObject(Object o, Class<T> destinationClass){
        return BeanCopier.copyJSONObject(o,destinationClass);
    }

    public  <T> List<T> convertList(Object o, Class<T> destinationClass){
        return  BeanCopier.copyJSONList(o,destinationClass);
    }
}
